package com.example.ktapplication.model
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.elvishew.xlog.XLog
import com.example.ktapplication.AppGlobals
import com.example.ktapplication.bean.HomeBannerBean
import com.example.ktapplication.state.HomeBannerState
import com.example.ktapplication.utils.NetworkUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import com.example.ktapplication.net.NetRepository

class BannerViewModel : ViewModel() {

    private val _state = MutableStateFlow<HomeBannerState>(HomeBannerState.OnSuccess(null))
    val state: StateFlow<HomeBannerState> = _state

    fun getHomeBannerData() {
        viewModelScope.launch {
            banner.flowOn(Dispatchers.IO)
                .catch { exception ->
                    _state.value = HomeBannerState.OnError(exception)
                }
                .collect { data ->
                    _state.value = HomeBannerState.OnSuccess(data)
                }
        }
    }

    private val banner: Flow<HomeBannerBean> = flow {
        if (!NetworkUtils.isConnected(AppGlobals.getApplication())){
            throw RuntimeException("网络未连接")
        }
        //网络请求
        val banner = NetRepository.instance.service.getHomeBanner()
        //返回结果
        emit(banner)
    }

    override fun onCleared() {
        super.onCleared()
    }
}